<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加角色区域 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRole = true">添加角色</el-button>
        </el-col>
      </el-row>

      <!-- 角色列表区域 -->
      <el-table :data="roleList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['dbbottom', i1 === 0 ? 'dbtop' : '','vcenter']"
              v-for="(item1,i1) in scope.row.children"
              :key="i1"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <!-- 通过for循环,嵌套渲染二级权限 -->
                <el-row
                  :class="[i2 === 0 ? '' : 'dbtop','vcenter']"
                  v-for="(item2, i2) in item1.children"
                  :key="i2"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row,item2.id)"
                    >{{ item2.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="(item3,i3) in item2.children"
                      :key="i3"
                      closable
                      @close="removeRightById(scope.row,item3.id)"
                    >{{ item3.authName }}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <pre></pre>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope" width="300px">
            <el-button
              size="mini"
              @click="editRoleBtn(scope.row.id)"
              type="primary"
              icon="el-icon-edit"
            >编辑</el-button>
            <el-button
              size="mini"
              @click="removeRoleById(scope.row.id)"
              type="danger"
              icon="el-icon-delete"
            >删除</el-button>
            <el-button
              size="mini"
              @click="showSetRightDialog(scope.row)"
              type="warning"
              icon="el-icon-setting"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配权限的对话框 -->
    <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="50%">
      <!-- 树形控件 -->
      <!-- 
          data:绑定的数据
          props:树形对象的属性绑定对象
          show-checkbox:开启节点前的复选框
          node-key:每个节点的唯一属性值
          default-expand-all:默认让树形控件以展开的格式展示
      -->
      <el-tree
        :data="rightsList"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加角色的对话框 -->
    <el-dialog title="添加角色" :visible.sync="addRole" width="50%" @close="addRoleClose">
      <!-- 内容主体区域 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRole = false">取 消</el-button>
        <el-button type="primary" @click="addRoleBtn">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑角色的对话框 -->
    <el-dialog title="编辑角色" :visible.sync="editRole" width="50%" @close="editRoleClose">
      <!-- 内容主体区域 -->
      <el-form :model="editForm" :rules="addFormRules" ref="editFormRef" label-width="70px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRole = false">取 消</el-button>
        <el-button type="primary" @click="confirmEditRoleBtn(editForm.roleId)">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 所有角色列表
      roleList: [],
      // 控制添加角色对话框的显示与隐藏
      addRole: false,
      //   控制修改用户对话框的显示与隐藏
      editRole: false,
      //   控制分配权限对话框的显示与隐藏
      setRightDialogVisible: false,
      //   添加角色的表单数据
      addForm: {
        roleName: "",
        roleDesc: ""
      },
      //   修改角色的表单数据
      editForm: {},
      //   所有权限的数据
      rightsList: [],
      //   树形控件的属性绑定对象
      treeProps: {
        label: "authName",
        children: "children"
      },
      //   默认选中的节点Id值数组
      defKeys: [],
      //   当前要分配权限的角色id
      roleId: "",
      //   添加角色的验证规则对象
      addFormRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          {
            min: 1,
            max: 10,
            message: "角色名的长度在1~10个字符之间",
            trigger: "blur"
          }
        ]
      }
    };
  },
  created() {
    this.getRoleList();
  },
  methods: {
    getRoleList() {
      this.$http.get("roles").then(res => {
        var res = res.data;
        if (res.meta.status !== 200) {
          this.$message.error("获取角色列表数据失败");
        }
        this.roleList = res.data;
      });
    },
    // 根据id删除对于的权限
    removeRightById(role, rightId) {
      // 弹窗提示用户是否删除
      this.$confirm("此操作将删除权限, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(res => {
          this.$http.delete(`roles/${role.id}/rights/${rightId}`).then(res => {
            var res = res.data;
            if (res.meta.status !== 200) {
              return this.$message.error("删除权限失败");
            }
            //   this.getRoleList()  会重新渲染整个表格,效果不好
            role.children = res.data;
          });
        })
        .catch(err => {
          this.$message.info("取消删除");
        });
    },
    // 监听角色对话框的关闭事件,清楚验证
    addRoleClose() {
      this.$refs.addFormRef.resetFields();
    },
    // 确认添加角色按钮的监听
    addRoleBtn() {
      // validate进行表单的验证规则校验
      this.$refs.addFormRef.validate(valid => {
        if (!valid) return;
        this.$http.post("roles", this.addForm).then(res => {
          var res = res.data;
          if (res.meta.status !== 201) {
            this.$message.error("添加角色失败");
          }
          this.$message.success("添加角色成功");
          // 隐藏添加角色的弹出框
          this.addRole = false;
          // 重新获取角色列表
          this.getRoleList();
        });
      });
    },
    // 展示编辑角色的对话框
    editRoleBtn(id) {
      this.editRole = true;
      this.$http.get("roles/" + id).then(res => {
        var res = res.data;
        if (res.meta.status !== 200) {
          return this.$message.error("获取角色数据失败");
        }
        this.editForm = res.data;
        this.editRole = true;
      });
    },
    // 监听修改角色对话框的关闭事件
    editRoleClose() {
      this.$refs.editFormRef.resetFields();
    },
    // 监听确认修改角色按钮
    confirmEditRoleBtn(id) {
      this.$refs.editFormRef.validate(valid => {
        if (!valid) return;
        this.$http
          .put("roles/" + id, {
            roleName: this.editForm.roleName,
            roleDesc: this.editForm.roleDesc
          })
          .then(res => {
            var res = res.data;
            if (res.meta.status !== 200) {
              this.$message.error("更新角色信息失败");
            }
            this.$message.success("更新角色信息成功");
            // 隐藏弹出的修改角色对话框
            this.editRole = false;
            // 重新获取角色列表
            this.getRoleList();
          });
      });
    },
    // 删除角色按钮监听事件
    removeRoleById(id) {
      // 提示用户是否确认删除
      this.$confirm("此操作将永久删除该角色信息, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(res => {
          this.$http.delete("roles/" + id).then(res => {
            var res = res.data;
            this.$message.success(res.meta.msg);

            //  重新获取角色列表数据
            this.getRoleList();
          });
        })
        .catch(err => {
          this.$message.info("取消删除");
        });
    },
    // 显示分配权限对话框
    showSetRightDialog(role) {
      // 将当前角色id存储到data中,方便后续给角色重新设置权限
      this.roleId = role.id;
      // 确保每次点击的时候当前的数组都是空的
      this.defKeys = [];
      // 获取所有树形权限数据
      this.$http.get("rights/tree").then(res => {
        var res = res.data;
        if (res.meta.status !== 200) {
          return this.$message.error("获取权限数据失败");
        }
        // 把权限数据保存到data中
        this.rightsList = res.data;
      });

      // 获取当前角色已拥有的权限id
      this.getLeafKeys(role, this.defKeys);

      this.setRightDialogVisible = true;
    },
    // 通过递归的形式,获取角色下所有三级权限的id,
    // 并保存到 defKeys数组中
    getLeafKeys(node, arr) {
      // 如果当前 node 节点不包含 children 属性,则是三级节点
      if (!node.children) {
        return arr.push(node.id);
      }
      // 如果当前不是三级节点则将当前节点的子节点进行迭代循环
      node.children.forEach(item => {
        this.getLeafKeys(item, arr);
      });
    },
    allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ];

      const idStr = keys.join(",");

      this.$http
        .post(`roles/${this.roleId}/rights`, { rids: idStr })
        .then(res => {
          var res = res.data;
          if (res.meta.status !== 200) {
            return this.$message.error("更新用户权限失败");
          }

          this.$message.success(res.meta.msg);
          this.getRoleList();
          // 将对话框隐藏
          this.setRightDialogVisible = false;
        });
    }
  }
};
</script>

<style lang="scss" scoped>
.el-tag {
  margin: 7px;
}

.dbtop {
  border-top: 1px solid #eee;
}

.dbbottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>